package com.example.portablefortheelderlybackground.sevice.Impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.portablefortheelderlybackground.common.key.paramsKey;
import com.example.portablefortheelderlybackground.mapper.weatherCityMapper;
import com.example.portablefortheelderlybackground.pojo.weather.weatherCity;
import com.example.portablefortheelderlybackground.sevice.weatherCityService;
import com.example.portablefortheelderlybackground.sevice.weatherDataService;
import com.example.portablefortheelderlybackground.vo.weatherVo.weatherVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
@Transactional(timeout = 3)
public class weatherCityServiceImpl extends ServiceImpl<weatherCityMapper, weatherCity> implements weatherCityService {
    private final weatherDataService weatherDataService;

    @Autowired
    public weatherCityServiceImpl(com.example.portablefortheelderlybackground.sevice.weatherDataService weatherDataService) {
        this.weatherDataService = weatherDataService;
    }


    @Override
    public Boolean getWeatherByWeek(String cityId, String appId, String appSecret) {
        String url = "https://v0.yiketianqi.com/free/week?unescape=1&appid=" + appId + "&appsecret=" + appSecret + "&cityid=" + cityId;
        //1.创建restTemplate模版,发送请求
        RestTemplate restTemplate = new RestTemplate();
        weatherVo forObject = restTemplate.getForObject(url, weatherVo.class);
        assert forObject != null;
        weatherCity weatherCity = new weatherCity();
        //2.拷贝属性
        boolean flag = true;
        BeanUtils.copyProperties(forObject, weatherCity, "data");
        flag = baseMapper.insert(weatherCity) > paramsKey.NUM_ZERO;
        if (!ObjectUtils.isEmpty(forObject.getData())) {
            flag = weatherDataService.saveBatch(forObject.getData());
        }
        return flag;
    }
}
